/*
 * @Author: rock
 * @Date: 2025-04-17 11:52:58
 * @LastEditors: rock 
 * @LastEditTime: 2025-04-17 17:09:31
 * @FilePath: /004epoll/src/initsock.cpp
 * @Description:
 *
 * Copyright (c) 2025 by rock, All Rights Reserved.
 */

#include "initsock.h"

void initsock(int &lfd)
{
    // 创建server监听套接字
    lfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == lfd)
    {
        std::string str = "socket err";
        err_str_out_(str);
        return ;
    }

    // 绑定IP地址和端口号
    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    // serv_addr.sin_port = PORT;
    serv_addr.sin_port = htons(PORT);//host to net short 本地字节序转网络字节序
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    // serv_addr.sin_addr.s_addr = INADDR_ANY;//host to net long 本地字节序转网络字节序

    // 设置端口复用
    int opt = 1;
    setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    // 绑定端口
    int ret = bind(lfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
    if (-1 == ret)
    {
        err_str_out_("bind err");
        exit(-1);
    }

    // 监听
    ret = listen(lfd, 128);
    if (-1 == ret)
    {
        err_str_out_("listen err");
        exit(-1);
    }

    std::cout << "server listen fd success!" << std::endl;
}
